package com.qf.filter;

/**
 * @author 孙亚梅
 * @version V1.0
 * @Project javase2203
 * @Package com.qf.filter
 * @Description:
 * @Date 2022/5/23 10:44
 */

import com.qf.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 鉴权过滤器
 * 拦截所有请求，判断tomcat的session中是否有用户对象信息
 * 如果有放行
 * 如果没有，说明用户为登录，重定向到登录页面，重新登录
 */
@WebFilter("/*")
public class PermFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1:获取用户的访问路径
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //2:获取到用户访问路径
        String uriStr = request.getRequestURI();
        System.out.println("======uriStr=====" + uriStr);


        //2:判断用户路径，放行所有静态资源，放行用户登录的路径，放行用户注册，首页，商品查询等路径
        //判断路径的扩展名，如果是js文件放行，因为js文件和jsp文件相差一个字母，使用contains

        if (uriStr.lastIndexOf(".") > 0) {
            String extStr = uriStr.substring(uriStr.lastIndexOf("."));
            if (extStr != null) {
                if (".js".equals(extStr)) {
                    //放行
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
            }
        }
        if (uriStr.contains("/login") ||uriStr.contains("/code")
                || uriStr.contains("/user") || uriStr.contains("/register")
                || uriStr.contains("/type")  || uriStr.contains("/goods")
                || uriStr.contains("/index")
                || uriStr.contains(".css") || uriStr.contains("/admin")
                || uriStr.contains(".jsp")|| uriStr.contains(".png")
                || uriStr.contains(".gif")|| uriStr.contains(".eot")
                || uriStr.contains(".svg")|| uriStr.contains(".ttf")
                || uriStr.contains(".woff")|| uriStr.contains(".woff2")){
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

            //3：获取会话session对象
            HttpSession session = request.getSession();

            //4:判断会话中是否有用户的对象信息
            User user = (User) session.getAttribute("loginUser");

            if (user != null) {
                //5有放行
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                //6：没有，让用户重定向到登录页面重新登录
                response.sendRedirect("/login.jsp");
            }

        }


    @Override
    public void destroy() {

    }
}
